package com.cc.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cc.common.utils.PageUtils;
import com.cc.common.utils.Query;
import com.cc.gulimall.product.dao.CategoryDao;
import com.cc.gulimall.product.entity.CategoryEntity;
import com.cc.gulimall.product.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        /*这里的baseMapper就是CategoryDao，因为当前Impl继承了ServiceImpl<CategoryDao, CategoryEntity>
        而继承时传入的泛型就是CategoryDao，而ServiceImpl里就是将CategoryDao取名为baseMapper*/
        List<CategoryEntity> entities = baseMapper.selectList(null);

        List<CategoryEntity> collect = entities.stream().filter(categoryEntity -> {
            //找到一级菜单
            return categoryEntity.getParentCid() == 0;
            //调用方法递归查询子类
        }).peek((menu) -> menu.setChildren(getChildrens(menu, entities))).
                sorted((menu1, menu2) -> {
                    return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
                }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 递归查询子类
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        //现在all里面找到某个实例的子类
        List<CategoryEntity> collect = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).peek(categoryEntity -> {
            //找到后递归查找子类的子类
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            //排序
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

}